<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">地点审核</h2>
      <el-button type="primary" :icon="Refresh" @click="loadData">刷新</el-button>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon pending">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ pagination.total }}</div>
            <div class="stat-label">待审核</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        :default-sort="{ prop: 'createdAt', order: 'descending' }"
      >
        <el-table-column type="index" label="#" width="60" />

        <el-table-column prop="name" label="地点名称" min-width="150">
          <template #default="{ row }">
            <div class="location-name">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="坐标位置" min-width="180">
          <template #default="{ row }">
            <el-text type="info" size="small">
              X: {{ row.coordinateX }}, Y: {{ row.coordinateY }}
            </el-text>
          </template>
        </el-table-column>

        <el-table-column prop="creator" label="创建者" min-width="150">
          <template #default="{ row }">
            <div v-if="row.creator" class="creator-info">
              <el-avatar :size="32" :src="row.creator.avatarUrl || undefined">
                {{ row.creator.nickname?.[0] || '?' }}
              </el-avatar>
              <span>{{ row.creator.nickname || '匿名用户' }}</span>
            </div>
            <el-text v-else type="info">未知</el-text>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="提交时间" min-width="180" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-button
                type="success"
                size="small"
                :icon="Select"
                @click="handleApprove(row)"
              >
                通过
              </el-button>
              <el-button
                type="danger"
                size="small"
                :icon="CloseBold"
                @click="handleReject(row)"
              >
                拒绝
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 地点详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="地点详情"
      width="600px"
      destroy-on-close
    >
      <el-descriptions v-if="currentLocation" :column="2" border>
        <el-descriptions-item label="地点名称">{{ currentLocation.name }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentLocation.status)">
            {{ getStatusText(currentLocation.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="X坐标">{{ currentLocation.coordinateX }}</el-descriptions-item>
        <el-descriptions-item label="Y坐标">{{ currentLocation.coordinateY }}</el-descriptions-item>
        <el-descriptions-item label="创建者" :span="2">
          {{ currentLocation.creator?.nickname || '匿名用户' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDateTime(currentLocation.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Clock,
  Refresh,
  Select,
  CloseBold
} from '@element-plus/icons-vue'
import { getLocations, approveLocation, rejectLocation } from '@/api/location'
import type { Location, LocationStatus } from '@/types/api'

// 数据状态
const loading = ref(false)
const tableData = ref<Location[]>([])
const currentLocation = ref<Location | null>(null)
const detailDialogVisible = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

/**
 * 加载数据
 */
async function loadData() {
  loading.value = true
  try {
    const response = await getLocations({
      status: 'PENDING' as LocationStatus,
      page: pagination.page,
      limit: pagination.limit
    })

    if (response.success) {
      tableData.value = response.data
      pagination.total = response.pagination.total
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 通过审核
 */
async function handleApprove(location: Location) {
  try {
    await ElMessageBox.confirm(
      `确定要通过"${location.name}"的审核吗？`,
      '确认通过',
      {
        confirmButtonText: '通过',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    loading.value = true
    const response = await approveLocation(location.id)

    if (response.success) {
      ElMessage.success('审核通过')
      loadData()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('审核通过失败:', error)
      ElMessage.error(error.message || '操作失败')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 拒绝审核
 */
async function handleReject(location: Location) {
  try {
    await ElMessageBox.confirm(
      `确定要拒绝"${location.name}"的审核吗？`,
      '确认拒绝',
      {
        confirmButtonText: '拒绝',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    const response = await rejectLocation(location.id)

    if (response.success) {
      ElMessage.success('已拒绝')
      loadData()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('拒绝失败:', error)
      ElMessage.error(error.message || '操作失败')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 页码改变
 */
function handlePageChange(page: number) {
  pagination.page = page
  loadData()
}

/**
 * 每页数量改变
 */
function handleSizeChange(size: number) {
  pagination.limit = size
  pagination.page = 1
  loadData()
}

/**
 * 获取状态类型
 */
function getStatusType(status: LocationStatus) {
  const typeMap = {
    PENDING: 'warning',
    APPROVED: 'success',
    REJECTED: 'danger'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取状态文本
 */
function getStatusText(status: LocationStatus) {
  const textMap = {
    PENDING: '待审核',
    APPROVED: '已通过',
    REJECTED: '已拒绝'
  }
  return textMap[status] || status
}

/**
 * 格式化日期时间
 */
function formatDateTime(dateString: string) {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.page-container {
  background: transparent;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #303133;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.pending {
  background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
  color: #fff;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 表格样式 */
.location-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.creator-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
